//
//  EatLayer.cpp
//  IceCreamSundae
//
//  Created by luotianqiang1 on 16/5/26.
//
//

#include "EatLayer.h"
#include "FoodData.h"
#include "AblumLayer.h"
#include "LQ_adLoadingLayer.h"
#include "MyDialog.h"
#include "ChooseLayer.h"
#include "TouchNodeComponent.h"
#include "particleLayer.h"
REGIST_SECENE(EatLayer)

const int EatLayer::eyeActionTag = 1111;
void EatLayer::playVoice(){
    vector<string> paths = {
        "sound/Voice Over/tasty.mp3",
        "sound/Voice Over/yummy.mp3"
    };
    
    if(voiceSound%8==0){
        voiceSound = 0;
        SoundPlayer::getInstance()->playEffect(paths.at(rand()%paths.size()));
    }
    voiceSound++;
}


bool EatLayer::init(){
    if(BaseStepLayer::init()) {
        isEatEnd = false;
        isDrinkEnd = true;
        voiceSound = 1;
        _operate = StudioLayer::create("EatLayer.csb");
        addChild(_operate);
        auto hideNodes = {"cup_shadow","cupDown"};
        for(auto name:hideNodes){
            auto node = _operate->getNodeByName(name);
            if(node)
                node->setVisible(false);
        }
        isPlay = false;
     
        return true;
    }
    return false;
}



void EatLayer::touchEnd(ui::Widget* widge){
    if(widge->getName().compare("btn_pre") == 0){
        Director::getInstance()->popScene();
    } else if(widge->getName().compare("btn_camer") == 0){
        saveAbumle();
        SoundPlayer::getInstance()->playEffect("sound/camera.mp3");
    } else if(widge->getName().compare("eat_again")==0){
        auto layer = EatLayer::create();
        auto scene = Scene::create();
        scene->addChild(layer);
        Director::getInstance()->replaceScene(scene);
    }else if(widge->getName().compare("btn_next") == 0){
        Director::getInstance()->popToRootScene();
        Director::getInstance()->replaceScene(TransitionPageTurn::create(1.2, ChooseLayer::createScene(),false));
    }
}

void EatLayer::onExitTransitionDidStart(){
    BaseStepLayer::onExitTransitionDidStart();
    for(auto eat:eats)
        eat->removeFromParent();
    eats.clear();
    
}


void EatLayer::onEnterTransitionDidFinish(){
    BaseStepLayer::onEnterTransitionDidFinish();
    //    auto eye = _operate->getNodeByName<Sprite*>("eye");
    //    eye->stopActionByTag(eyeActionTag);
    //    auto action = RepeatForever::create(Sequence::create(CallFunc::create([eye](){
    //        eye->setSpriteFrame("PNG/4_eat/girl_eye0.png");
    //    }), DelayTime::create(2),CallFunc::create([eye](){
    //        eye->setSpriteFrame("PNG/4_eat/girl_eye1.png");
    //    }),DelayTime::create(0.3), nullptr));
    //    action->setTag(eyeActionTag);
    //    eye->runAction(action);
    _eventDispatcher->setEnabled(false);
    _eatAgainPos = _operate->getNodeByName("eat_again")->getPosition();
    SoundPlayer::getInstance()->playEffect("sound/general/ingredients_fly_in.mp3");
    vector<string> btnName = {"btn_home","btn_camer","btn_pre"};
    SoundPlayer::getInstance()->playEffect("sound/ingredients_fly_in.mp3");
    vector<ActionHelper::ShowDirection> der = {ActionHelper::ShowDirection::show_from_left,ActionHelper::ShowDirection::show_from_right,ActionHelper::ShowDirection::show_from_left};
    for(int i=0;i<btnName.size();i++){
        auto btn = _operate->getNodeByName(btnName[i]);
        ActionHelper::showBackInOut(btn, btn->getPosition(), der[i],[=](){
            if(i == btnName.size() -1) {
                //                auto names = {"girl","girl2","girl3"};
                //                for(auto name:names){
                //                    auto girl = _operate->getNodeByName(name);
                //                    auto pos = girl->getPosition();
                //                    girl->setVisible(true);
                //                    ActionHelper::setStartPostion(girl, pos, ActionHelper::ShowDirection::show_from_right);
                //                    girl->runAction(MoveTo::create(1, pos));
                //                }
                initFood();
            }
        });
        btn->setVisible(true);
    }
    
    
}

void EatLayer::saveAbumle(){
    Director::getInstance()->getEventDispatcher()->setEnabled(false);
    _operate->getNodeByName("uiLayer")->setVisible(false);
    auto cupDown = _operate->getNodeByName("cupDown");
    auto _size = Director::getInstance()->getVisibleSize();
    auto _render = RenderTexture::create(_size.width, _size.height, Texture2D::PixelFormat::RGBA8888, GL_DEPTH24_STENCIL8);
    cupDown->setScale(0.75);
    _render->begin();
    visit();
    _render->end();
    Director::getInstance()->getRenderer()->render();
     cupDown->setScale(1);
    _operate->getNodeByName("uiLayer")->setVisible(true);
    auto _layer = AblumLayer::create();
    _layer->setMaskPath("ui/ui_photo/photo1.png");
    addChild(_layer,30);
    _layer->setRender(_render);
    SoundPlayer::getInstance()->playEffect("sound/general/pop_up_open.mp3");
}

void EatLayer::checkEnd(){
  //  check->eatPercentageCallback = nullptr;
    this->unschedule(schedule_selector(EatLayer::caculteEat));
    //    auto eye = _operate->getNodeByName<Sprite*>("eye");
    //    eye->stopActionByTag(eyeActionTag);
    //    eye->setSpriteFrame("PNG/4_eat/girl_eye3.png");
    //    ActionHelper::delayFunc(0.4, this, [this](){
    //
    //        _operate->getNodeByName<ParticleSystemQuad*>("heartPartcile")->resetSystem();
    //    });
    //    ActionHelper::delayFunc(1, this, [=](){
    //        auto action = RepeatForever::create(Sequence::create(CallFunc::create([eye](){
    //            eye->setSpriteFrame("PNG/4_eat/girl_eye0.png");
    //        }), DelayTime::create(2),CallFunc::create([eye](){
    //            eye->setSpriteFrame("PNG/4_eat/girl_eye1.png");
    //        }),DelayTime::create(0.3), nullptr));
    //        action->setTag(eyeActionTag);
    //        eye->runAction(action);
    //    });
    
    auto next = _operate->getNodeByName("btn_next");
    ActionHelper::showBackInOut(next, next->getPosition(), ActionHelper::ShowDirection::show_from_right);
    next->setVisible(true);
    auto _eatAgain = _operate->getNodeByName<ui::Button*>("eat_again");
    if(_eatAgain!= nullptr&&!_eatAgain->isVisible()){
        _operate->playNodeSound(_eatAgain->getName());
        ActionHelper::showBackInOut(_eatAgain, _eatAgainPos, ActionHelper::ShowDirection::show_from_top);
        _eatAgain->setVisible(true);
        _eatAgain->setEnabled(true);
    }
    
}

void EatLayer::caculteEat(float){
    isPlay = false;
    //    auto eye = _operate->getNodeByName<Sprite*>("eye");
    //    eye->stopActionByTag(eyeActionTag);
    //    auto action = RepeatForever::create(Sequence::create(CallFunc::create([eye](){
    //        eye->setSpriteFrame("PNG/4_eat/girl_eye0.png");
    //    }), DelayTime::create(2),CallFunc::create([eye](){
    //        eye->setSpriteFrame("PNG/4_eat/girl_eye1.png");
    //    }),DelayTime::create(0.3), nullptr));
    //    action->setTag(eyeActionTag);
    //    eye->runAction(action);
}

void EatLayer::initFood(){
    vector<string> decNames = {"cup","straw"};
    for(auto decName:decNames){
        auto decs =  FoodData::getDecoration(decName);
        if(decs.size()>0){
            auto decNode = _operate->getNodeByName<Sprite*>(decName+"Dec");
            decNode->setSpriteFrame(dynamic_cast<Sprite*>(decs.at(0))->getSpriteFrame());
            decNode->setScale(decs.at(0)->getScale());
            decNode->setPosition(decs.at(0)->getPosition());
        }
    }
    
    SoundPlayer::getInstance()->playEffect("sound/general/ingredients_fly_in.mp3");
    auto cupDown = _operate->getNodeByName("cupDown");
    ActionHelper::showBezier(cupDown, cupDown->getPosition(), ActionHelper::ShowDirection::show_from_left,[=](){
        auto cup_shadow = _operate->getNodeByName("cup_shadow");
        cup_shadow->setLocalZOrder(-1);
        CocosHelper::reAddNode(cup_shadow, cupDown);
        cup_shadow->setVisible(true);
        cup_shadow->setOpacity(0);
        cup_shadow->runAction(FadeIn::create(0.2f));
        _eventDispatcher->setEnabled(true);
        ActionHelper::showTitle(_operate->getNodeByName("title"),ActionHelper::ShowDirection::show_from_top);
    },0.9f);
    cupDown->setVisible(true);
    
 
    auto touchNode = _operate->getNodeByName("toucNode");
    auto touchEvent = TouchNodeComponent::create();
    touchNode->addComponent(touchEvent);
    touchEvent->addListners(ComponentTouchBegan, [=](LQComponent*,OperateListner*){
        touchEvent->playSound();
        for(auto drink:eats)
            drink->resumAction();
    });
    touchEvent->addListners(ComponentTouchCancle, [=](LQComponent*,OperateListner*){
        touchEvent->stopSound();
        for(auto drink:eats)
            drink->pasuAction();
    });
    touchEvent->addListners(ComponentTouchEnd, [=](LQComponent*,OperateListner*){
        touchEvent->playSound();
        touchEvent->stopSound();
        for(auto drink:eats)
            drink->pasuAction();
    });
    auto inCupPaths = FoodData::getInCupPath();
    auto eatContainer = _operate->getNodeByName("eatContainer");
    auto path = FileUtils::getInstance()->getWritablePath()+"fileImage.png";
    if(FileUtils::getInstance()->isFileExist(FileUtils::getInstance()->fullPathForFilename(path))){
        auto drink = KDS::ShadeSprite::create(path, inCupPaths[0]);
        drink->setPosition(eatContainer->getContentSize()*.5);
        eatContainer->addChild(drink);
        drink->setDistance(400);
        eats.pushBack(drink);
        drink->endCallback = [=](KDS::ShadeSprite*){
            drink->getSrcSprite()->setVisible(false);
        };
    }
    
    auto eatContainer0 = _operate->getNodeByName("eatContainer0");
    auto drink = KDS::ShadeSprite::create(inCupPaths[0], inCupPaths[0]);
    drink->setPosition(eatContainer0->getContentSize()*.5);
    eatContainer0->addChild(drink);
    drink->setDistance(400);
    eats.pushBack(drink);
    drink->endCallback = [=](KDS::ShadeSprite*){
        drink->getSrcSprite()->setVisible(false);
        isEatEnd = true;
        touchEvent->stopSound();
        touchEvent->setEnabled(false);
        checkEnd();
    };
    
   
    
    
}